package com.cqrt.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class TreeProcessor {

    /**
     * 从 FastJSON 的 JSONObject 中提取 sourceActiveOid 和 UID 的对应关系
     */
    public static Map<String, String> extractSourceActiveOidAndUid(JSONObject jsonObject) {
        Map<String, String> result = new HashMap<>();

        // 处理顶层任务数组
        if (jsonObject.containsKey("Tasks")) {
            JSONArray tasksArray = jsonObject.getJSONArray("Tasks");
            processTasks(tasksArray, result);
        }

        return result;
    }


    public static Set<String> extractAllUIds(JSONObject jsonObject) {
        Set<String> result = new HashSet<>();

        // 处理顶层任务数组
        if (jsonObject.containsKey("Tasks")) {
            JSONArray tasksArray = jsonObject.getJSONArray("Tasks");
            collectUIds(tasksArray, result);
        }

        return result;
    }

    /**
     * 递归处理任务数组
     */
    private static void processTasks(JSONArray tasksArray, Map<String, String> result) {
        if (tasksArray == null) return;

        for (Object taskObj : tasksArray) {
            if (!(taskObj instanceof JSONObject)) continue;

            JSONObject task = (JSONObject) taskObj;

            // 提取当前任务的 sourceActiveOid 和 UID
            String sourceActiveOid = task.getString("sourceActiveOid");
            String uid = task.getString("UID");

            // 仅当两个值都有效时存储
            if (sourceActiveOid != null && uid != null) {
                result.put(sourceActiveOid, uid);
            }

            // 递归处理子任务
            JSONArray childrenArray = task.getJSONArray("children");
            processTasks(childrenArray, result);
        }
    }

    private static void collectUIds(JSONArray tasksArray, Set<String> result) {
        if (tasksArray == null)
            return;

        for (Object taskObj : tasksArray) {
            if (!(taskObj instanceof JSONObject)) continue;

            JSONObject task = (JSONObject) taskObj;

            // 提取当前任务的 UID
            String uid = task.getString("UID");

            // 仅当 UID 有效时存储
            if (uid != null) {
                result.add(uid);
            }

            // 递归处理子任务
            JSONArray childrenArray = task.getJSONArray("children");
            collectUIds(childrenArray, result);
        }
    }
}